import Vue from 'vue';

/**
 * 初始化Token
 *
 * @param {*} callback
 * @param {*} failback
 */
async function initAppToken(callback, failback) {
  rt.setRequestHeaders('Platform', 'app');
  await refreshToken(null, callback, failback);
  initInterceptor();
}

/**
 * 刷新Token
 * @param {*} config
 * @param {*} callback
 * @param {*} failback
 */
function refreshToken(config, callback, failback) {
  var address = window.location.origin;
  clearAuth();
    var address = window.location.origin;
    rt.get(`${address}/static/config.json`).then(function (res) {
      rt.setBaseURL(res.SERVER_URL);
      rt.get('/api/apptoken')
      .then((res) => {
        if (res) {
          let accessToken = res.accessToken;
          let refreshToken = res.refreshToken;
          let resetTime = res.expiresIn;
          let curentTime = new Date().getTime();
          sessionStorage.setItem('resetTime', curentTime + resetTime * 1000);
          let auth = {
            accessToken,
            refreshToken,
          };
          Vue.store.commit('UPDATE_AUTH', auth);
          if (callback) {
            callback();
          }
          if (config) {
            return retry(config);
          }
        }
      })
      .catch((err) => {
        if (failback) {
          failback();
        }
        return Promise.reject(err);
      });
    });
}
/**
 * 清除认证数据
 */
function clearAuth() {
  Vue.store.commit('UPDATE_AUTH', {});
}
/**
 * 设置请求拦截器和响应拦截器
 */
function initInterceptor() {
  rt.setRequestInterceptors((config) => {
    if (Vue.store.getters.isLoggedIn) {
      config.headers.Authorization = Vue.store.getters.authorization;
    }

    return config;
  });
  rt.setResponseInterceptors(undefined, (error) => {
    if (isTokenExpired()) {
      refreshToken(error.config);
    }
    return Promise.reject(error);
  });
}
/**
 * 判断token是否过期
 */
function isTokenExpired() {
  let expires_time = sessionStorage.getItem('resetTime');
  let curentTime = new Date().getTime();
  if (curentTime >= expires_time) {
    return true;
  } else {
    return false;
  }
}
/**
 * 从新调用请求
 * @param {*} config
 */
function retry(config) {
  return rt.request(config);
}

export { initAppToken };
